{% extends "user/user-base.html" %}

{% block user_media %}
    {% include "timezone/media-css.html" %}
    {{ form.media.css }}
    <style>
        .sortedm2m-container, .sortedm2m-container p.selector-filter {
            width: 300px;
        }

        .sortedm2m-container p.selector-filter input {
            width: 262px;
        }

        ul.sortedm2m {
            width: 284px;
            min-height: 70px;
            max-height: 200px;
            height: 70px
        }

        .inline-header {
            float: left;
            font-size: 1.1em;
            padding: 4px 8px;
            padding-left: 0;
        }

        .block-header {
            font-size: 1.1em;
        }

        .block-buttons {
            margin: 0.5em 0 0.8em;
        }

        .fullwidth {
            display: block;
            overflow: hidden;
        }

        #edit-form {
            border: unset;
            background: unset;
            display: block;
            padding-bottom: 30px;
        }

        .settings {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
        }

        .pane {
            display: block;
            width: 337px;
        }

        .api-token {
            padding-top: 5px;
            font-family: Consolas, Liberation Mono, Monaco, Courier New, monospace;
            font-size: 12px;
            -webkit-user-select: all;
            -ms-user-select: all;
            user-select: all;
            white-space: nowrap;
        }

        .ml-5 {
            margin-left: 5px;
        }

        #hidden-word {
            padding-top: 5px;
            font-family: Consolas, Liberation Mono, Monaco, Courier New, monospace;
            font-size: 12px;
        }

        #scratch-codes {
            font-family: Consolas, Liberation Mono, Monaco, Courier New, monospace;
            font-size: 12px;
            white-space: pre;
        }

        #scratch-codes-text {
            padding-top: 5px;
            font-size: 12px;
        }
    </style>
{% endblock %}

{% block js_media %}
    {% include "timezone/media-js.html" %}
    {{ form.media.js }}
    <script type="text/javascript">
        $(function () {
            $('#ace_user_script').on('ace_load', function (e, editor) {
                editor.getSession().setMode("ace/mode/javascript");
            });

            $('#disable-2fa-button').click(function () {
                alert({{ _('The administrators for this site require all the staff to have Two-factor Authentication enabled, so it may not be disabled at this time.')|htmltojs }});
            });

            $('#generate-api-token-button').click(function (event) {
                event.preventDefault();
                if (confirm({{ _('Are you sure you want to generate or regenerate your API token?')|htmltojs }} + '\n'
                          + {{ _('This will invalidate any previous API tokens.')|htmltojs }} + ' '
                          + {{ _('It also allows access to your account without Two-factor Authentication.')|htmltojs }} + '\n\n'
                          + {{ _('You will not be able to view your API token after you leave this page!')|htmltojs }})) {
                    $('#api-token').text({{ _('Generating...')|htmltojs }});

                    $.ajax({
                        type: 'POST',
                        url: $(this).attr('href'),
                        dataType: 'json',
                        success: function(data) {
                            $('#api-token').text(data.data.token);
                            $('#generate-api-token-button').text({{ _('Regenerate')|htmltojs }});

                            // Add remove button on-the-fly
                            if ($('#remove-api-token-button').length == 0) {
                                $('#generate-api-token-button').after($('<a id="remove-api-token-button" \
                                    href="{{ url('remove_api_token') }}" \
                                    class="button inline-button ml-5">{{ _('Remove') }}</a>'));
                            }
                        },
                    });
                }
            });

            // Delegated event handler because the remove button may have been added on-the-fly
            $('#api-token-td').on('click', '#remove-api-token-button', function (event) {
                event.preventDefault();
                if (confirm({{ _('Are you sure you want to remove your API token?')|htmltojs }})) {
                    $.ajax({
                        type: 'POST',
                        url: $(this).attr('href'),
                        dataType: 'json',
                        success: function(data) {
                            $('#api-token').text('');
                            $('#generate-api-token-button').text({{ _('Generate')|htmltojs }});
                            $('#remove-api-token-button').remove();
                        },
                    });
                }
            });
        });
    </script>
    <script>
        // This is basically impossible to write without ES6, hence separate script block.
        $(() => {
            {% include "user/webauthn-helpers.js" %}

            $('#new-webauthn').click(event => {
                event.preventDefault();

                if (typeof window.PublicKeyCredential === 'undefined') {
                    alert({{ _('WebAuthn is not supported by your browser.')|htmltojs }});
                    return;
                }

                $.getJSON('{{ url('webauthn_attest') }}')
                    .done(publicKey => {
                        decodeJSONBytes(publicKey);
                        navigator.credentials.create({publicKey})
                            .then(credential => {
                                credential = {
                                    id: credential.id,
                                    response: {
                                        attObj: urlSafeBase64Encode(credential.response.attestationObject),
                                        clientData: urlSafeBase64Encode(credential.response.clientDataJSON),
                                    }
                                };
                                $.post('{{ url('webauthn_attest') }}', {
                                    credential: JSON.stringify(credential),
                                    name: $('#new-webauthn-name').val(),
                                })
                                    .then(() => window.location.reload())
                                    .fail((jqXHR) => alert(jqXHR.responseText));
                            });
                    })
                    .fail(() => alert({{ _('Failed to contact server.')|htmltojs }}));
            });

            $('.webauthn-delete').click(function (event) {
                event.preventDefault();
                if (confirm({{ _('Are you sure you want to delete this security key?')|htmltojs }})) {
                    $.post($(this).attr('data-delete-url'))
                        .then(() => window.location.reload())
                        .fail((jqXHR) => alert(jqXHR.responseText));
                }
            });
        });
    </script>
    <script src="{{ static('libs/clipboard/clipboard.js') }}"></script>
    <script src="{{ static('libs/clipboard/tooltip.js') }}"></script>
    <script type="text/javascript">
        $(function () {
            $('#generate-scratch-codes-button').click(function(event) {
                event.preventDefault();
                if (confirm({{ _('Are you sure you want to generate or regenerate a new set of scratch codes?')|htmltojs }} + '\n'
                          + {{ _('This will invalidate any previous scratch codes you have.')|htmltojs }} + '\n\n'
                          + {{ _('You will not be able to view your scratch codes after you leave this page!')|htmltojs }})) {
                    $('#scratch-codes').text({{ _('Generating...')|htmltojs }});

                    $('pre code').each(function () {
                        var copyButton;
                        $(this).parent().before($('<div>', {'class': 'copy-clipboard'})
                            .append(copyButton = $('<span>', {
                                'class': 'btn-clipboard',
                                'id': 'scratch-codes-copy-button',
                                'data-clipboard-text': '',
                                'title': {{ _('Click to copy')|htmltojs }}
                            }).text({{ _('Copy')|htmltojs }})));

                        $(copyButton.get(0)).mouseleave(function () {
                            $(this).attr('class', 'btn-clipboard');
                            $(this).removeAttr('aria-label');
                        });

                        var curClipboard = new Clipboard(copyButton.get(0));

                        curClipboard.on('success', function(e) {
                            e.clearSelection();
                            showTooltip(e.trigger, {{ _('Copied!')|htmltojs }});
                        });

                        curClipboard.on('error', function(e) {
                            showTooltip(e.trigger, fallbackMessage(e.action));
                        });
                    });

                    $.ajax({
                        type: 'POST',
                        url: $(this).attr('href'),
                        dataType: 'json',
                        success: function(data) {
                            $('#scratch-codes').text(data.data.codes.join('\n'));
                            $('#scratch-codes-copy-button').attr('data-clipboard-text', data.data.codes.join('\n'));
                            $('#generate-scratch-codes-button').text({{ _('Regenerate')|htmltojs }});
                            $('#hidden-word').hide();
                            $('#scratch-codes-regen').show();
                        },
                    });
                }
            });
        });
    </script>
{% endblock %}

{% block title_ruler %}{% endblock %}

{% block title_row %}
    {% set tab = 'edit' %}
    {% set user = request.profile %}
    {% include "user/user-tabs.html" %}
{% endblock %}

{% block body %}
    <div class="centered-form">
        <form id="edit-form" action="" method="post" class="form-area">
            {% if form.errors %}
                <div class="alert alert-danger alert-dismissable">
                    <a href="#" class="close">x</a>
                    {{ form.non_field_errors() }}
                    {{ form.about.errors }}
                </div>
            {% endif %}

            {% csrf_token %}

            <div style="padding-top:0.5em" class="block-header grayed">{{ _('Self-description:') }}</div>
            {{ form.about }}
            <hr>

            <div class="settings" style="padding-top:0.7em">
                <div class="pane" style="vertical-align:top">
                    <table style="padding-right:0.8em">
                        <tr title="{{ _('Select your closest major city') }}">
                            <td><label class="inline-header grayed">{{ _('Time zone:') }}</label></td>
                            <td><span class="fullwidth">{{ form.timezone }}</span></td>
                        </tr>
                        <tr>
                            <td><label class="inline-header grayed">{{ _('Language:') }}</label></td>
                            <td><span class="fullwidth">{{ form.language }}</span></td>
                        </tr>
                        <tr{% if not perms.judge.test_site %} style="display: none"{% endif %}>
                            <td><label class="inline-header grayed">{{ _('Site theme:') }}</label></td>
                            <td><span class="fullwidth">{{ form.site_theme }}</span></td>
                        </tr>
                        <tr>
                            <td><label class="inline-header grayed">{{ _('Editor theme:') }}</label></td>
                            <td><span class="fullwidth">{{ form.ace_theme }}</span></td>
                        </tr>
                        {% if has_math_config %}
                            <tr>
                                <td><label class="inline-header grayed">{{ _('Math engine:') }}</label></td>
                                <td><span class="fullwidth">{{ form.math_engine }}</span></td>
                            </tr>
                        {% endif %}
                    </table>
                </div>
                {% if form.organizations %}
                    <div class="pane">
                        <div style="padding-bottom:0.3em; margin-top:0.3em" class="block-header grayed">
                            {{- _('Affiliated organizations:') -}}
                        </div>
                        {{ form.organizations }}
                    </div>
                {% endif %}
            </div>
            <hr>
            <div class="settings" style="padding-top:0.7em">
                <div class="pane">
                    <table border="0">
                        {% if form.newsletter %}
                            <tr><td>
                                {{ form.newsletter }}
                                <label for="id_newsletter" style="float: unset" class="inline-header grayed">
                                        {{- _('Notify me about upcoming contests') -}}
                                </label>
                            </td></tr>
                        {% endif %}
                        <tr><td>
                            {{ form.test_site }}
                            <label for="id_test_site" style="float: unset" class="inline-header grayed">
                                {{- form.test_site.label -}}
                            </label>
                        </td></tr>
                        <tr><td>
                            <a href="https://www.gravatar.com/" target="_blank" class="inline-header" rel="noopener">
                                {{ _('Change your avatar') }}
                            </a>
                        </td></tr>
                        <tr><td>
                            <a href="{{ url('password_change') }}" class="inline-header">
                                {{ _('Change your password') }}
                            </a>
                        </td></tr>
                        <tr><td>
                            <a href="{{ url('email_change') }}" class="inline-header">
                                {{ _('Change your email') }}
                            </a>
                        </td></tr>
                        {% if can_download_data %}
                            <tr><td>
                                <a href="{{ url('user_prepare_data') }}" class="inline-header">
                                    {{ _('Download your data') }}
                                </a>
                            </td></tr>
                        {% endif %}
                        <tr><td>
                            <span id="api-token-td" class="inline-header grayed">
                                {{ _('API token:') }}
                                {% if profile.api_token %}
                                    <a id="generate-api-token-button" href="{{ url('generate_api_token') }}"
                                        class="button inline-button">{{ _('Regenerate') }}</a>
                                    <a id="remove-api-token-button" href="{{ url('remove_api_token') }}"
                                        class="button inline-button ml-5">{{ _('Remove') }}</a>
                                    <div class="api-token" id="api-token">{{ _('Hidden') }}</div>
                                {% else %}
                                    <a id="generate-api-token-button" href="{{ url('generate_api_token') }}"
                                        class="button inline-button">{{ _('Generate') }}</a>
                                    <div class="api-token" id="api-token"></div>
                                {% endif %}
                            </span>
                        </td></tr>
                    </table>
                </div>
                <div class="pane">
                    <div>
                        {% if profile.is_totp_enabled %}
                            <div class="block-header grayed">{{ _('Two-factor authentication is enabled:') }}</div>
                            <div class="block-buttons">
                                {% if require_staff_2fa and request.user.is_staff and not profile.is_webauthn_enabled %}
                                    <a id="disable-2fa-button" class="button inline-button">{{ _('Disable') }}</a>
                                {% else %}
                                    <a href="{{ url('disable_2fa') }}"
                                       class="button inline-button">{{ _('Disable') }}</a>
                                {% endif %}
                                <a href="{{ url('edit_2fa') }}" class="button inline-button">{{ _('Edit') }}</a>
                            </div>
                            <div class="block-header grayed">
                                {{ _('Scratch codes:') }}
                                {% if profile.scratch_codes %}
                                    <a id="generate-scratch-codes-button" href="{{ url('generate_scratch_codes') }}"
                                       class="button inline-button">{{ _('Regenerate') }}</a>
                                    <div id="hidden-word">{{ _('Hidden') }}</div>
                                {% else %}
                                    <a id="generate-scratch-codes-button" href="{{ url('generate_scratch_codes') }}"
                                       class="button inline-button">{{ _('Generate') }}</a>
                                {% endif %}
                                <div style="display: none" id="scratch-codes-regen">
                                    <div id="scratch-codes-text">
                                        {{ _('Below is a list of one-time use scratch codes.') }}
                                        {{ _('These codes can only be used once and are for emergency use.') }}
                                        {{ _('You can use these codes to login to your account or disable two-factor authentication.') }}
                                        {{ _('If you ever need more scratch codes, you can regenerate them here.') }}
                                        {{ _('Please write these down and keep them in a secure location.') }}<br><br>
                                        {{ _('You will not be able to view your scratch codes after you leave this page!') }}</div>
                                    <pre><code id="scratch-codes"></code></pre>
                                </div>
                            </div>
                        {% else %}
                            <span class="inline-header grayed">
                                {{ _('Two-factor Authentication is disabled:') }}
                                <a href="{{ url('enable_2fa') }}" class="button inline-button">{{ _('Enable') }}</a>
                            </span>
                        {% endif %}
                    </div>
                    <span class="grayed">
                    {% if HAS_WEBAUTHN %}
                        <div style="padding-bottom:0.4em" class="block-header grayed">
                            {{- _('Security keys:') -}}
                        </div>
                        <table class="table">
                            {% if profile.is_webauthn_enabled %}
                                {% for credential in profile.webauthn_credentials.all() %}
                                    <tr>
                                        <td>{{ credential.name }}</td>
                                        <td>
                                            <button class="webauthn-delete inline-button"
                                                    data-delete-url="{{ url('webauthn_delete', credential.id) }}">
                                                {{ _('Delete') }}
                                            </button>
                                        </td>
                                    </tr>
                                {% endfor %}
                            {% endif %}
                            <tr>
                                <td><input id="new-webauthn-name" type="text" placeholder="{{ _('Enter a name for this key') }}"></td>
                                <td><button id="new-webauthn" class="inline-button">{{ _('Add') }}</button></td>
                            </tr>
                        </table>
                    {% endif %}
                    </span>
                </div>
            </div>
            <hr>
            <div class="block-header grayed">{{ _('User-script:') }}</div>
            {{ form.user_script }}
            <hr>

            <input type="submit" class="submit-bar" value="{{ _('Update profile') }}">
        </form>
    </div>
{% endblock %}
